<template>
  <div>
    <el-dialog
      customClass="customWidth"
      @close="handleClose"
      :lock-scroll="false"
      close-on-press-escape
      v-dialogDrag
      title="添加点位"
      :close-on-click-modal="false"
      :visible.sync="showDialog"
    >
      <el-form
        class="points"
        :model="pointsForm"
        :rules="rules"
        ref="pointsForm"
        label-width="40%"
        size="mini"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="点位名称" prop="name">
              <el-input v-model="pointsForm.name" placeholder="请输入点位名称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Token" prop="token">
              <el-input v-model="pointsForm.token" placeholder="请输入Token">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="pointsForm.unit" placeholder="请输入单位">
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="点位说明" prop="description">
              <el-input
                v-model="pointsForm.description"
                placeholder="请输入点位说明"
              >
              </el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="数据类型" prop="type">
              <el-select v-model="pointsForm.type" placeholder="请输入数据类型">
                <el-option
                  v-for="(item, index) in optionType"
                  :key="index"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="事件类型" prop="comments">
              <el-select
                v-model="pointsForm.comments"
                placeholder="请输入事件类型"
              >
                <el-option
                  v-for="(item, index) in event"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="访问权限" prop="permission">
              <el-radio-group v-model="pointsForm.permission">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-radio label="只读"></el-radio>
                  </el-col>
                  <el-col :span="12">
                    <el-radio label="读/写"></el-radio>
                  </el-col>
                </el-row>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="图表展示" prop="isChart">
              <el-select
                multiple
                v-model="pointsForm.isChart"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in POINT_CHART_TYPES"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="btns_ref_add">
          <el-button
            size="small"
            @click="resetForm('pointsForm')"
            icon="el-icon-refresh-left"
            >重置
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="addPointsForm('pointsForm')"
            icon="el-icon-plus"
            style="background: #2680d2"
            >添加</el-button
          >
        </div>
      </el-form>

      <!-- 点位tables -->
      <el-table
        style="width: 100%"
        height="200"
        :data="
          pointsTable.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )
        "
        ref="pointsTable"
      >
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="token" label="Token"> </el-table-column>
        <el-table-column prop="description" label="说明"> </el-table-column>
        <el-table-column prop="type" label="数据类型"> </el-table-column>
        <el-table-column prop="comments" label="事件类型">
          <template slot-scope="scope">
            {{ convert(scope.row.comments) }}
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="访问权限"> </el-table-column>
        <el-table-column prop="isChart" label="图表展示">
          <template slot-scope="scope">
            {{ renderChartText(scope.row.isChart) }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="tab_btn">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click.native.prevent="handleDelete(scope.$index, pointsTable)"
              >
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--本地table分页 -->
      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="pointsTable.length"
      >
      </el-pagination>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancel">取 消</el-button>
        <el-button
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm"
          style="background: #2680d2"
        >
          确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { TOKEN_RULES } from "@/utils/local";
import { addPoints, getDeviceTypeAttributes } from "@/api/deviceType";
import { POINT_CHART_TYPES } from "@/utils/local";
export default {
  props: {
    addPointsshow: {
      type: Boolean,
      default: false
    },
    deviceTypeToken: {
      type: String,
      default: ""
    },
    token: {
      type: String,
      default: ""
    }
  },
  computed: {
    renderChartText() {
      return function(type) {
        const options = POINT_CHART_TYPES.filter(item =>
          type.includes(item.key)
        );
        const labels = options.map(item => item.label);
        return labels.join(",");
      };
    }
  },
  data() {
    return {
      POINT_CHART_TYPES,
      btnLoading: false,
      showDialog: false,
      pointsForm: {
        isChart: [],
        unit: "",
        name: "",
        // description: "",
        type: "",
        permission: "",
        comments: "",
        token: ""
      },
      pointsTable: [],
      rules: {
        name: [
          { required: true, message: "请输入点位名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur"
          }
        ],
        token: TOKEN_RULES,
        // description: [
        //   { required: true, message: "请输入点位说明", trigger: "blur" },
        //   {
        //     min: 1,
        //     max: 15,
        //     message: "长度在 1 到 15 个字符",
        //     trigger: "blur"
        //   }
        // ],
        type: [
          {
            type: "string",
            required: true,
            message: "请选择数据类型",
            trigger: "change"
          }
        ],

        unit: [
          {
            type: "string",
            required: true,
            message: "请输入点位",
            trigger: "change"
          }
        ],
        comments: [
          {
            type: "string",
            required: true,
            message: "请选择事件类型",
            trigger: "change"
          }
        ],
        permission: [
          { required: true, message: "请选择访问权限", trigger: "change" }
        ]
      },
      optionType: [
        { value: "0", label: "TIMESTAMP" },
        { value: "1", label: "INT" },
        { value: "2", label: "BIGINT" },
        { value: "3", label: "FLOAT" },
        { value: "4", label: "DOUBLE" },
        { value: "5", label: "BINARY(20)" },
        { value: "6", label: "SMALLINT" },
        { value: "7", label: "TINYINT" },
        { value: "8", label: "BOOL" },
        { value: "9", label: "NCHAR(20)" }
        // { value: "10", label: "Char" },
        // { value: "11", label: "Byte" },
        // { value: "12", label: "Short" },
        // { value: "13", label: "Word" },
      ],
      event: [
        { value: "Measurement", label: "遥测" },
        { value: "Location", label: "位置" },
        { value: "Alert", label: "告警" },
        { value: "CommandInvocation", label: "命令调用" },
        { value: "CommandResponse", label: "命令响应" },
        { value: "StateChange", label: "设备状态" }
      ],
      // deviceTypeToken: this.$route.query.deviceTypeToken,
      pageSize: 5,
      currentPage: 1,
      change: 1
    };
  },
  watch: {
    addPointsshow(oldVal, newVal) {
      this.showDialog = this.addPointsshow;
    }
  },
  mounted() {},
  methods: {
    convert(row) {
      if (row == "Measurement") {
        return "遥测";
      } else if (row == "Location") {
        return "位置";
      } else if (row == "Alert") {
        return "告警";
      } else if (row == "CommandInvocation") {
        return "命令调用";
      } else if (row == "CommandResponse") {
        return "命令响应";
      } else if (row == "StateChange") {
        return "设备状态";
      }
    },
    // 关闭
    handleClose() {
      Object.assign(this.$data.pointsForm, this.$options.data().pointsForm);
      this.pointsTable = [];
      this.$nextTick(() => {
        this.$refs["pointsForm"].clearValidate();
        this.$emit("changeShow", "false");
      });
    },
    // 提交
    submitForm() {
      let formData = [];
      this.pointsTable.forEach(item => {
        let tableData = {
          name: item.name,
          // description: item.description,
          deviceTypeToken: this.deviceTypeToken,
          type: item.type,
          permission: item.permission,
          deviceEventType: item.comments,
          // token: this.token + "_" + item.token,
          token: item.token,
          unit: item.unit,
          isChart: item.isChart.join(",")
        };
        formData.push(tableData);
      });
      // TODO:限制无数据时不能点击确定
      if (!this.pointsTable.length) {
        this.$message({
          type: "warning",
          message: "尚未填写点位信息"
        });
        return false;
      } else {
        this.btnLoading = true;
        addPoints(formData, this.deviceTypeToken)
          .then(res => {
            this.$msg({
              type: "success",
              message: "操作成功!"
            });
            this.$emit("updatePointsList");
            Object.assign(
              this.$data.pointsForm,
              this.$options.data().pointsForm
            );
            // this.pointsForm = {
            //   name: "",
            //   description: "",
            //   type: "",
            //   permission: "",
            //   comments: "",
            //   token: ""
            // };
            this.pointsTable = [];
            this.showDialog = false;
          })
          .finally(f => {
            this.btnLoading = false;
          });
      }
    },
    cancel() {
      this.showDialog = false;
      // this.pointsForm = {
      //   name: "",
      //   description: "",
      //   type: "",
      //   permission: "",
      //   comments: "",
      //   token: ""
      // };
      Object.assign(this.$data.pointsForm, this.$options.data().pointsForm);
      this.pointsTable = [];
    },
    // 重置表单
    resetForm(pointsTable) {
      this.$refs[pointsTable].resetFields();
    },
    // 表单本地添加
    addPointsForm(pointsForm) {
      let that = this;
      // let change;
      this.$refs[pointsForm].validate(valid => {
        if (valid) {
          let newData = {
            ...this.pointsForm
            // name: this.pointsForm.name,
            // description: this.pointsForm.description,
            // type: this.pointsForm.type,
            // permission: this.pointsForm.permission,
            // comments: this.pointsForm.comments,
            // token: this.pointsForm.token
          };

          for (let i = 0; i < this.pointsTable.length; i++) {
            if (that.pointsForm.token == that.pointsTable[i].token) {
              that.$message({
                type: "error",
                message:
                  "已存在此点位Token:" + that.pointsForm.token + ", 新重新输入!"
              });
              return false;
            }
          }

          // 查询是否有重复token
          getDeviceTypeAttributes({}, this.deviceTypeToken).then(res => {
            let arrToken = [];
            res.data.results.forEach(item => {
              arrToken.push(item.token);
            });

            for (let i = 0; i < arrToken.length; i++) {
              if (newData.token == arrToken[i]) {
                that.$message({
                  type: "error",
                  message:
                    "已存在此点位Token:" + newData.token + ", 请重新输入!"
                });
                return false;
              }
            }
            that.pointsTable.push(newData);
          });

          this.$nextTick(() => {
            this.$refs["pointsForm"].clearValidate();
          });
          Object.assign(this.$data.pointsForm, this.$options.data().pointsForm);
          // this.pointsForm = {
          //   name: "",
          //   description: "",
          //   type: "",
          //   permission: "",
          //   comments: "",
          //   token: ""
          // };
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单本地删除
    handleDelete(index, row) {
      row.splice(index, 1);
    },
    //列表分页
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  }
};
</script>

<style scoped>
.btns_ref_add {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.customWidth {
  width: 80%;
}
.points {
  margin-left: -15px;
}
.tab_btn .el-button--text {
  color: red;
}
</style>
